package com.campus.happy;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;

import com.nostra13.universalimageloader.core.ImageLoader;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.widget.ImageView;

public class Load {
	public static Bitmap cache;
     public static Context context;
	public static void down(ImageView img, String url) {
//		ConnectivityManager connectMgr = (ConnectivityManager) 
//		       context .getSystemService(Context.CONNECTIVITY_SERVICE);
//		 
//		 NetworkInfo info = connectMgr.getActiveNetworkInfo();
//		if( info.getType()==0)
//			return;
		
		go(img, url);
		// ImageLoader.getInstance().displayImage(url,img);
	}

	static void go(final ImageView img, final String url) {
		try {

			final File file = new File(
					Environment.getExternalStorageDirectory() + "/pack/"
							+ url.hashCode());
			if (file.exists()) {

				Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
				if (img.getTag().equals(url))
					img.setImageBitmap(bm);
				File p = new File(Environment.getExternalStorageDirectory()
						+ "/pack/");
           if(p.list().length>100)
				{
				FileUtils.deleteDir(p);

				}
			} else {
				File f = new File(Environment.getExternalStorageDirectory()
						+ "/pack/");
				if (!f.exists()) {
					f.mkdirs();

				}
				if(cache!=null)
				{
					img.setImageBitmap(cache);
				}
				new Thread() {
					public void run() {
						try {
							final byte[] b = CookieHttp.get(url);
							new FileOutputStream(file).write(b);
							Handler handler = new Handler(
									Looper.getMainLooper());
							handler.post(new Runnable() {

								@Override
								public void run() {
									// TODO Auto-generated method stub
									Bitmap bm = BitmapFactory.decodeByteArray(
											b, 0, b.length);
									if (img.getTag().equals(url))
										img.setImageBitmap(bm);
								}
							});
						} catch (MalformedURLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				}.start();

			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
